<?php

namespace app\common\model\product;

use think\Model;
// 引用 软删除
use traits\model\SoftDelete;
class Product extends Model
{
    // 产品表
    protected $table = 'pre_product';

     // 软删除时间
     use SoftDelete;
     protected $deleteTime = 'deletetime';

    protected $append = [
        'cover_cdn',
        'thumbs_cdn',
        'vip_price'
    ];

    public function getCoverCdnAttr($value, $data)
    {
        // $cdn = config('cdn');

        $cdn = model('Config')->where(['key' => 'SiteUrl'])->value('value');

        $thumbs = empty($data['thumbs']) ? [] : trim($data['thumbs']);
        if (empty($thumbs)) {
            return $cdn . '/static/admin/images/noPro.png';
        }
        //字符串替换
        $thumbs = str_replace("uploads/", $cdn . "/uploads/", $thumbs);
        // return $thumbs;
        //在转换为数组
        // $list = explode(',', $thumbs);
        $list = json_decode($thumbs, true);

        if (count($list) > 0) {
            return $list[0];
        }
    }

    public function getThumbsCdnAttr($value, $data)
    {
        // $cdn = config('cdn');
        $cdn = model('Config')->where(['key' => 'SiteUrl'])->value('value');

        $thumbs = empty($data['thumbs']) ? [] : trim($data['thumbs']);

        if (empty($thumbs)) {
            return [$cdn . 'static/home/res/images/avatar/default.png'];
        }

        //字符串替换
        $thumbs = str_replace("uploads/", $cdn . "/uploads/", $thumbs);

        //在转换为数组
        // $list = explode(',', $thumbs);
        $list = json_decode($thumbs, true);

        return $list;
    }

    public function getVipPriceAttr($value, $data)
    {
        // 这里接收的用户id
        $userid = request()->param('userid', 0);

        // 商品id
        $proid = $data['id'];

        // 查询当前用户的vip等级
        $UserVip = model('User.User')->where(['id' => $userid])->value('vip');

        if (!$UserVip) {
            return 0;
        }
        $price = model('Product.ProductVip')->where(['proid' => $proid, 'level' => $UserVip])->value('price');
        if (!$price) {
            return 0;
        }
        return $price;
    }

    // 关联查询: 商品分类
    public function ProductType()
    {
        return $this->belongsTo('app\common\model\Product\ProductType', 'typeid', 'id', [], 'LEFT')->setEagerlyType(0);
    }

}
